import type { Router } from 'vue-router'
import { useUserStoreWithOut } from '@/store/modules/user'
import { PageEnum } from '@/enums/pageEnum'
import { RootRoute } from '@/router/basic'

const LOGIN_PATH = PageEnum.BASE_LOGIN
const HOME_PATH = PageEnum.BASE_HOME
const ROOT_PATH = RootRoute.path
const whitePathList: PageEnum[] = [LOGIN_PATH]

export interface RedirectData {
  path: string,
  replace: boolean,
  query?: Recordable
}

export function createPermissionGuard(router: Router) {
  const userStore = useUserStoreWithOut()
  router.beforeEach(async (to, from, next) => {
    if (
      from.path === ROOT_PATH &&
      to.path === PageEnum.BASE_HOME &&
      userStore.getUserInfo.homePath &&
      userStore.getUserInfo.homePath !== PageEnum.BASE_HOME
    ) {
      next(userStore.getUserInfo.homePath);
      return;
    }

    const token = userStore.getToken;

    if (whitePathList.includes(to.path as PageEnum)) {
      if (to.path === LOGIN_PATH && token) {
        next((to.query?.redirect as string) || HOME_PATH)
        return
      }
      next()
      return
    }
    if (!token) {
      // redirect login page
      const redirectData: RedirectData = {
        path: LOGIN_PATH,
        replace: true,
      }
      next(redirectData)
      return
    }
    next()
  })
}
